<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="账号信息"></u-navbar> -->

		<free-list-item title="登录账号" :showRight="false" :showRightIcons="false" :showLeftIcon="false">
			<text slot="right" class="font-12 text-muted">{{ifdUser.enterpriseName}}</text>
		</free-list-item>
		<free-list-item title="绑定手机号" :showRight="false" :showLeftIcon="false" @click="update('bindPhone')">
			<text slot="right" class="font-14 text-muted ursrRight">{{ifdUser.phone}}</text>
		</free-list-item>

		<free-list-item title="登录密码" :showRight="false" :showLeftIcon="false" @click="update('Password')">
			<text slot="right" class="font-14 text-muted ursrRight">{{maskedPassword}}</text>
		</free-list-item>
		<!-- 修改名字|修改微信号 弹框-->
		<free-confirm ref="confirm" :title="confirmTitle">
			<view class="pl-1">
				<u-form :model="form" ref="uForm">
					<u-form-item required  label="原密码" label-width="120" prop="oldPassword">
						<u-input class="mr-3 " :password-icon="true" type="password" placeholder="请输入原密码"
							v-model="form.oldPassword" input-align="right" />
					</u-form-item>
					<u-form-item required  label="新密码" label-width="120" prop="newPassword">
						<u-input class="mr-3 " :password-icon="true" type="password" placeholder="请输入新密码"
							v-model="form.newPassword" input-align="right" />
					</u-form-item>
					<u-form-item required  label="确认新密码" label-width="180" prop="confirmPassword">
						<u-input class="mr-3 " :password-icon="true" type="password" placeholder="请再次输入密码"
							v-model="form.confirmPassword" input-align="right" />
					</u-form-item>
					<view class="font-12 mt-1" style="color: red;">由英文、数字、特殊字符中的至少2种组成，不少于6位</view>
				</u-form>
			</view>
		</free-confirm>
		<!-- 修改手机号码 弹框-->
		<free-confirm ref="confirmShow" :title="confirmPhomTitle">
			<u-form :model="form">
				<u-form-item :label-style="labelStyle" label="手机号码" label-width="180" prop="phone">
					<u-input class="mr-3 " placeholder="请输入所绑定的手机号" v-model="code.phone" input-align="right" />
				</u-form-item>
				<u-form-item :label-style="labelStyle" label="验证码" label-width="180" prop="captcha">
					<u-input class="mr-3 " placeholder="请输入验证码" v-model="code.captcha" input-align="right" />
					<u-button size="mini" slot="right" type="warning" @click="getCode">{{codeText}}</u-button>
				</u-form-item>
			</u-form>
			<u-toast ref="uToast"></u-toast>
			<u-verification-code :seconds="seconds" @end="end" @start="start" ref="uCode"
				@change="codeChange"></u-verification-code>
		</free-confirm>
	</view>
</template>

<script>
	import $H from '@/common/free-lib/request.js';
	import freeListItem from "@/components/free-ui/free-list-item.vue";
	import freeDivider from "@/components/free-ui/free-divider.vue";
	import freeConfirm from "@/components/free-ui/free-confirm.vue";
	export default {
		components: {
			freeListItem,
			freeDivider,
			freeConfirm
		},
		data() {
			return {
				codeText: '',
				confirmType: "",
				mobile: '', // 手机号
				code: '', // 验证码
				seconds: 60,
				ifdUser: {},
				form: {
					confirmPassword: "",
					newPassword: "",
					oldPassword: "",
				},
				labelStyle: {
					paddingLeft: '13px',
					width: '130px'
				},
				code: {
					phone: '',
					captcha: ''
				},
				rules: {
					oldPassword: [{
							required: true,
							message: '原密码不能为空',
							trigger: ['change', 'blur'],
						},
						{
						    validator: (rule, value, callback) => {
						        // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
						        const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
						        if (!reg.test(value)) {
						            callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
						        } else {
						            callback();
						        }
						    },
						    trigger: ['change', 'blur'],
						}
					],
					newPassword: [{
							required: true,
							message: '新密码不能为空',
							trigger: ['change', 'blur'],
						},
						{
						    validator: (rule, value, callback) => {
						        // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
						        const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
						        if (!reg.test(value)) {
						            callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
						        } else {
						            callback();
						        }
						    },
						    trigger: ['change', 'blur'],
						}
					],
					confirmPassword: [{
							required: true,
							message: '确认新密码不能为空',
							trigger: ['change', 'blur'],
						},
						{
						    validator: (rule, value, callback) => {
						        // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
						        const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
						        if (!reg.test(value)) {
						            callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
						        } else {
						            callback();
						        }
						    },
						    trigger: ['change', 'blur'],
						}
					],
				},
			}
		},
		computed: {
			confirmTitle() {
				return this.confirmType == 'username' ? '修改密码' : '修改昵称'
			},
			confirmPhomTitle() {
				return this.confirmType == 'username' ? '更换手机号' : '更换手机号'
			},
			placeholder() {
				return this.confirmType == 'username' ? '输入账号' : '输入名称'
			},
			maskedPassword() {
				// 如果 this.ifdUser 不存在或者 username 为空，则返回空字符串
				if (!this.ifdUser || !this.ifdUser.username) {
					return '';
				}
				// 否则将密码替换为星号
				return this.ifdUser.username.replace(/./g, "******");
			}
		},
		onLoad(options) {
			const id = options.id;
			this.NewUser(id)
		},
		mounted() {
		  if (this.$refs.uForm) {
		    this.$refs.uForm.setRules(this.rules);
		  }
		},
		methods: {
			codeChange(text) {
				this.codeText = text;
			},
			getCode() {
				if (this.getCodeisWaiting) {
					return;
				}

				// 隐藏键盘
				uni.hideKeyboard();
				this.getCodeText = "发送中...";
				this.getCodeisWaiting = true;
				let o = {
					phone: this.code.phone
				};

				// 发送请求获取验证码
				$H.get('/brand/user/agriculture/randomImage', o)
					.then(res => {
						uni.showToast({
							title: '验证码已发送',
							icon: "none"
						});
						if (this.$refs.uCode.canGetCode) {
							uni.showLoading({
								title: '正在获取验证码'
							});
							setTimeout(() => {
								uni.hideLoading();
								this.$refs.uCode.start();
							}, 2000);
						} else {
							this.$u.toast('倒计时结束后再发送');
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});
			},
			end() {
				this.$u.toast('倒计时结束');
				this.getCodeisWaiting = false;
			},
			start() {
				this.$u.toast('倒计时开始');
			},
			editePhone(id) {
				let o = {
					...this.code,
					id: this.id
				};
				$H.post('/brand/user/agriculture/editePhone', o, {
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
						}
					})
					.then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
							this.clearPhone();
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});
			},
			/**end  验证码**/


			/**start  修改密码**/
			changePassword(id) {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						let o = {
							...this.form,
							id: this.id
						};
						$H.post('/brand/user/agriculture/editPassword', o, {
								header: {
									'Content-Type': 'application/x-www-form-urlencoded',
								}
							})
							.then(res => {
								if (res.code === 200 && res.success) {
									uni.showToast({
										title: res.message,
										icon: 'none',
									});
									// 关闭弹框并清空数据
									this.clearData();

								} else {
									uni.showToast({
										title: res.message || '输入密码不正确',
										icon: 'error'
									});
								}
							})
							.catch(error => {
								uni.showToast({
									title: "网络错误，请稍后再试",
									icon: 'none'
								});
							});
					} else {
						uni.showToast({
							title: "请完整填写表单",
							icon: 'none'
						});
					}
				})
			},


			update(key) {
				const this_ = this;
				switch (key) {
					case 'Password':
						// 调用确认弹框
						this_.$refs.confirm.show(function(close) {
							this_.changePassword();
							// close();
						});
						break;
					case 'bindPhone':
						// 处理绑定手机号码逻辑，弹起弹框
						this_.confirmType = 'bindPhone';
						this_.$refs.confirmShow.show((close) => {
							this_.editePhone();
							close()
						})
						break;
					default:
						break;
				}
			},

			clearData() {
				// 清空表单数据
				this.form.confirmPassword = '';
				this.form.newPassword = '';
				this.form.oldPassword = '';
			},
			clearPhone() {
				this.code.phone = '';
				this.code.captcha = ''
			},
			/** end 修改密码**/
			NewUser(id) {
				$H.get('/brand/user/queryById', {
					id: id
				}, {}).then(res => {
					this.ifdUser = res.result
					this.id = res.result.id
				}).catch(error => {
					uni.showToast({
						title: "网络错误，请稍后再试",
						icon: 'none'
					});
				});
			},

		}

	}
</script>

<style>
</style>